package com.lry.netty01.server.utils;


import com.lry.netty01.server.Client;
import com.lry.netty01.server.entity.FixedFrame;
import com.lry.netty01.server.entity.Packet;
import com.lry.netty01.server.queue.Task;
import io.netty.channel.Channel;
import io.netty.util.concurrent.Future;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;


@Slf4j
public class CommandUtil {

    public static byte START = 0x10;

    public static byte END = 0x16;

    /****************************cmd******************************************/
     //1=注册包，2=心跳包，3=报警包，4=操作包
    public static byte REGISTER_CMD = 0x01;

    public static byte HEART_BEAT_CMD = 0x02;

    public static byte WARNING_CMD = 0x03;

    public static byte OPERATE_CMD = 0x04;

    /*****************************cmd*****************************************/



    static int requestTimeout = 10000;

    public static CompletableFuture<FixedFrame> registerResultFuture(short devId, Channel channel) throws InterruptedException {

        return CompletableFuture.supplyAsync(()->{
            if(!ChannelUtil.checkChannel(channel)){
                log.info(devId+"不在线");
                return null;
            }
            //发送注册报文
            Packet packet = new Packet(true,channel,new FixedFrame(CommandUtil.REGISTER_CMD,devId,(byte)0));
            packet.response = new FixedFrame();
            Client.offerTaskQueue(new Task(packet));
            try{
                synchronized (packet) {
                    //如果配置了请求超时时间
                    if (requestTimeout > 0) {
                        // Wait for request completion with timeout
                        waitForPacketFinish(packet);
                    } else {
                        //没有配置的话就死等请求完成
                        // Wait for request completion infinitely
                        while (!packet.finished) {
                            packet.wait();
                        }
                    }
                }
            }catch(Exception e){

            }
            return packet.response;
        });

    }

    //注册结果同步拿到
    public static FixedFrame registerResult(short devId, Channel channel) throws InterruptedException {
        if(!ChannelUtil.checkChannel(channel)){
            log.info(devId+"不在线");
            return null;
        }

        //发送注册报文
        Packet packet = new Packet(true,channel,new FixedFrame(CommandUtil.REGISTER_CMD,devId,(byte)0));
        packet.response = new FixedFrame();
        Client.offerTaskQueue(new Task(packet));

        synchronized (packet) {
            //如果配置了请求超时时间
            if (requestTimeout > 0) {
                // Wait for request completion with timeout
                waitForPacketFinish(packet);
            } else {
                //没有配置的话就死等请求完成
                // Wait for request completion infinitely
                while (!packet.finished) {
                    packet.wait();
                }
            }
        }

        return packet.response;
    }

    private static void waitForPacketFinish(Packet packet)
            throws InterruptedException {
        //等待开始时间
        long waitStartTime = Time.currentElapsedTime();
        //packet未完成就一直循环，直到完成跳出循环
        while (!packet.finished) {
            //先最多等待配置的超时时间
            packet.wait(requestTimeout);
            //如果还是未完成并且 时间超过了requestTimeout就break掉，不等了
            if (!packet.finished && ((Time.currentElapsedTime()
                    - waitStartTime) >= requestTimeout)) {
                log.error("Timeout error occurred for the packet '{}'.",
                        packet);
                //把超时包从临时队列移除
                ChannelUtil.pendingQueue.remove(packet);
                break;
            }
        }
    }


}
